import BScroll from '@better-scroll/core'; // 核心滚动
import Slide from '@better-scroll/slide'; // 滚动插件

import { onMounted, ref, onUnmounted } from 'vue'; // 引入钩子函数

// 注册插件
BScroll.use(Slide);

export default function useSlider(wrapperRef) {
  // slider DOM
  const slider = ref(null);
  // 当前图片下标
  const currentPageIndex = ref(0);
  // slider初始化
  onMounted(() => {
    // wrapperRef.value为对应的传入的元素的DOM对象
    const sliderValue = slider.value = new BScroll(wrapperRef.value, {
      click: true,
      scrollX: true,
      scrollY: false,
      momentum: false,
      bounce: false,
      probeType: 2,
      slide: true
    });
    // 底部圆点
    sliderValue.on('slideWillChange', (page) => {
      // pageX为当前轮播图的索引
      currentPageIndex.value = page.pageX;
    });
  });

  // 销毁slider
  onUnmounted(() => {
    slider.value.destroy();
  });

  return {
    slider,
    currentPageIndex
  };
}
